package com.aiit.controller;
import com.aiit.config.SendMail;
import com.aiit.pojo.ProcResult;
import com.aiit.pojo.User;
import com.aiit.service.impl.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Date;
import java.util.Random;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
@Slf4j
@Controller
public class CodeController {
	/**
	 * 验证码
	 */
	private String code;
	/**
	 * 发送时间
	 */
	private Date sendTime;
	@Resource
	private UserService userService;

	@PostMapping("/sendEmail")
    @ResponseBody
	public ProcResult getCode(User user){
		// 创建一个随机数生成器类
		System.out.println("sendEmail");
		code = SendMail.generateVerCode();
		System.out.println("*****"+code+"*****");
		//实例化一个发送邮件的对象
		SendMail mySendMail = new SendMail();
		sendTime = new Date();
		log.info("============>:sendTime"+sendTime);
		//根据邮箱找到该用户信息
		 user = userService.getUserByEmail(user);
		System.out.println(user);
		 if(user!=null) {
			//设置发送时间
			 //设置收件人和消息内容
			mySendMail.sendMail(user.getEmail(), "系统提醒，"+user.getUsername()+",您的验证码为："+ code);
		 }
		return ProcResult.success();
	}
	@PostMapping("view/modifyPwd")
	@ResponseBody
	public ProcResult modifyPwd(User user){
		Date date = new Date();
		log.info("============>date:"+date);
		log.info("============>SendMail.getMinute(sendTime, date):"+SendMail.getMinute(sendTime, date));
		log.info("============>!=:"+!code.equals(user.getCode()));
		System.out.println(user);
		if (SendMail.getMinute(sendTime, date) >= 1) {
			return ProcResult.fail().bind("msg","验证码已经失效！！！");
		}else if(user.getCode().equals(code)) {
			userService.forgetPwd(user);
			return ProcResult.success().bind("msg","修改成功");
		}
		return ProcResult.fail().bind("msg","验证码错误！");
	}
	@GetMapping("view/modifyPwd")
	public String modify(){

		return "view/modifyPwd";
	}
 
}
